<template>
   <div class="login-container">
    <el-form class="login-form" ref="login-form" :model="user" :rules="formRoles">
      <el-form-item prop="mobile">
        <el-input v-model="user.mobile" placeholder="请输入手机号"></el-input>
      </el-form-item>
      <el-form-item prop="code">
        <el-input v-model="user.code" placeholder="请输入验证码"></el-input>
      </el-form-item>
      <el-form-item prop="agree">
          <el-checkbox v-model="user.agree">我已阅读并同意用户协议和隐私条款</el-checkbox>
      </el-form-item>
      <el-form-item>
        <el-button class="login-btn" type="primary" :loading="loginLoading" @click="onLogin">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import request from '@/utils/request'
import { login } from '@/api/user'
export default {
  name:'LoginIndex',
  data () {
    return { 
      user: {
        mobile: "13911111111",
        code: "246810",
        agree: false
      },
      loginLoading: false,
      formRoles: {
           mobile: [
            { required: true, message: '手机号码不能为空', trigger: 'blur' },
            { min: 7, max: 11, message: '长度在 7 到 11 个字符', trigger: 'blur' },
            { pattern: /^1[1|3|5|7|8|9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'change' }
          ],
           code: [
            { required: true, message: '验证码不能为空', trigger: 'blur' },
            { pattern: /^\d{6}$/, message: '请输入正确的验证码格式' }
          ],
           agree: [
            { 
                validator: (rule, value, callback) => {
                    if (value) {
                        callback();
                    }else{
                        callback(new Error('请勾选用户协议'));
                    }
                }, 
                trigger: 'change'
            },
          ],
      }
    }
  },
  methods: { 
    onLogin() {
       this.$refs['login-form'].validate(valid => {
          if (!valid){
              return;
          }
          this.login();
       })
    },
    login () {
        this.loginLoading = true;
        login(this.user).then(res => {
            this.$message.success('登录成功！！！');
            this.loginLoading = false;
            window.localStorage.setItem('user',JSON.stringify(res.data.data));
            this.$router.push('/');
        }).catch(err => {
            this.$message.error('登录失败！！！');
            this.loginLoading = false;
        })
    }
  },
  created () {}
}
</script>
<style scoped lang="less">
.login-container{
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    background: url('./login_bg.jpg') no-repeat;
    background-size: cover;
    .login-form{
        background-color: #fff;
        padding: 50px;
        min-width: 300px;
        opacity: 0.75;
        .login-btn{
            width: 100%;
        }
    }
}
</style>